<template>
  <el-dialog
    title="编辑图文" :close-on-click-modal="false" :visible.sync="show"
    class="dialog_index dialog_banner dialog_image_new" id="imageText"  :before-close="cancle" >
    <el-form v-loading="loading" class="scroll imageText">
      <el-tabs type="card"  v-model="activeName">
        <el-tab-pane :label="item.site"  :name="item.site" v-for="(item, index) in list" :key="item.id">
          <!-- 预览模块 -->
          <div class="module_preview"> 
            <p>预览</p>
            <draggable  class="module_preview_content"  @end="(oldIndex,newIndex) => sortDraggable( index, oldIndex,newIndex)">
              <div class="item" v-for="(child, childI) in item.data"  :key="child.title_key" :class=" childI == curDataIndex?'active': ''" 
               @click="setCurDataItem(childI)">
                <span class="icon_delete" @click.stop="removeDataItem(childI)">
                  <i class="iconfont icon-delect_normal" title="删除"></i>
                  <!-- <svg class="icon-delect_normal" >
                    <use xlink:href="#icon-delect_normal"></use>
                  </svg>
                  <svg class="icon-delect_hover" >
                    <use xlink:href="#icon-delect_hover"></use>
                  </svg> -->
                </span>
                <div :class="[child.image_style] " >
                  <div v-for="(childSec, childSecI ) in child.data" :key="childSecI" class="" >
                    <div class="el-image" :class="childSec.image ? '': 'noImg'" :style="'background-image: url('+utils.setCdnUrl() + childSec.image+')'"></div>
                    <div class="inputWord">
                      <p class="title">{{childSec.title || '标题'}}</p>
                      <p class="description">{{childSec.description || '描述'}}</p>
                    </div>
              
                  </div>
                </div>
            

              </div>
            </draggable>
         
          </div>

          <div class="module_style">
            <p>样式</p> 
            <div class="swiper">
              <div :class="{'carousel-button-prev':true, 'disabled':curStyleIndex == 0}" @click="slidePrev" >
                <button type="button" class="el-carousel__arrow el-carousel__arrow--left"  >
                  <i class="el-icon-arrow-left"></i>
                </button>
              </div>
              <swiper :options="swiperOption" ref="mySwiper">
                <div v-for="(slide, index) in styleList" :key="index" class="styleItem swiper-no-swiping" :class="{'active':index == curStyleIndex}">
                  <!-- <div @click.stop.prevent="setCurstyleItem(slide ,index)" :class="{'active':index == curStyleIndex}"> -->
                  <div @click.stop.prevent="setCurstyleItem(slide ,index)">
                    <SvgIcon className="iconNormal" :iconClass="slide.iconNormal" :toggleClick="toggleSideBar"></SvgIcon> 
                    <i class="iconfont icon-select"></i>
                  </div>
                </div>
              </swiper>

              <div :class="{'carousel-button-next':true,'disabled':curStyleIndex == styleList.length-1 }" @click="slideNext">
                <button type="button" class="el-carousel__arrow el-carousel__arrow--right">
                  <i class="el-icon-arrow-right"></i>
                </button>
              </div>
    
            </div>
            <div class="module_style_content" >
              <div :class="item.curImageList[0].image_style">
                <div v-for="(content, contentI) in item.curImageList" :key="contentI" >
                  <el-upload class="upload-image" action="/api/api/general/upload"  
                  :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, contentI)"
                    :on-error="handleError" :before-upload="beforeUpload"
                  :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type:'product_image', imageheight: imgH, imagewidth: imgW}" >
                    <div class="upload_btn">
                      <el-button slot="trigger" size="small" type="primary" :loading="uploadLoading">本地上传</el-button>
                      <el-button size="small" type="primary" @click.stop="isCloseDrawer(contentI)">图库选择</el-button> 
                    </div>
             
                    <div class="pop_container"> 
                      <el-image v-if="content.image" :src="utils.setCdnUrl() + content.image" class="pop_image"></el-image>
                    </div>
                    <!-- 提示语要换 -->
                    <p class="tip" v-if="!content.image">{{tip}}</p>

                  </el-upload>
                  <div class="inputWord">
                    <el-input type="textarea" @change="(value) => changeTitle(value, index, contentI)" v-model="item.curImageList[contentI].title" :placeholder="'标题('+item.site+')（非必填项)'" resize="none" :rows="5"></el-input>
                    <el-input  type="textarea" @change="(value) => changeDescription(value, index, contentI)" v-model="content.description" :placeholder="'描述('+item.site+')（非必填项)'"  resize="none" :rows="5"></el-input>
                  </div>
                </div>
              </div>
         

            </div>

          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm" :loading="isRequest"
        >保存</el-button
      >
      <el-button @click="cancle">取消</el-button>
    </span>
    <Drawer
      v-show="showDrawer"
      :type="'product_image'"
      :show="showDrawer"
      @closeDialog="closeDrawerDialog"
    ></Drawer>
  </el-dialog>
</template>

<script>
import SvgIcon from '@/components/SvgIcon'

import Drawer from "@/components/Gallery/index.vue";
import { Swiper } from 'vue-awesome-swiper'
import { productImageGet , productImagePost} from "@/api/product/productBasic.js";
import draggable from 'vuedraggable'

export default {
  data() {
    return {
      list: [ ],
      styleList: [
          { name: 'imageTextStyle1-4',num: 1, style: '', iconNormal: 'icon-style1_1_hover'}, 
          { name: 'imageTextStyle1-3',num: 1, style: '', iconNormal: 'icon-style1_2_hover'}, 
          { name: 'imageTextStyle1-1',num: 1, style: '', iconNormal: 'icon-style1_3_hover'},
          { name: 'imageTextStyle1-5',num: 1, style: '', iconNormal: 'icon-style1_4_hover'}, 
          { name: 'imageTextStyle1-2',num: 1, style: '', iconNormal: 'icon-style1_5_hover'}, 
          { name: 'imageTextStyle1-6',num: 1, style: '', iconNormal: 'icon-style1_6_hover'}, 
          { name: 'imageTextStyle4-1',num: 1, style: '', iconNormal: 'icon-style1_7_hover'},
          { name: 'imageTextStyle4-2',num: 1, style: '', iconNormal: 'icon-style1_8_hover'},
          { name: 'imageTextStyle2-1',num: 2, style: '', iconNormal: 'icon-style2_1_hover'}, 
          { name: 'imageTextStyle2-2',num: 2, style: '', iconNormal: 'icon-style2_2_hover'}, 
          { name: 'imageTextStyle2-3',num: 2, style: '', iconNormal: 'icon-style2_3_hover'}, 
          { name: 'imageTextStyle3-1',num: 3, style: '', iconNormal: 'icon-style3_1_hover'}, 
          { name: 'imageTextStyle3-2',num: 3, style: '', iconNormal: 'icon-style3_2_hover'},
        ],
      swiperOption: {
        loop: false,
        direction: 'horizontal',
        spaceBetween: 16,
        height: 76,
        // slidesPerView: 8,
      },
      loading: false,
      uploadLoading: false,
      imgH: "",
      imgW: "",
      obj: {
        specification_name: "",
        image: "",
        title: "",
        description: "",
      },
      isRequest: false,
      showDrawer: false,
      index: 0,
      curStyleIndex: 0, // 当前选中样式的位置
      curStyleNum: 1, // 当前选中的样式的子元素
      curImageList: [], // 当前选中图文的数组
      curDataIndex: 0, // 当前图文位置
      activeName: 'US',
    };
  },
  props: {
    show: Boolean,
    closeDialog: Function,
    id: Number,
  },
  watch: {
    show: function () {
      if (this.show) {
        this.isRequest = false
        this.activeName = 'US'
        this.getProductImage()
      }
    },
  },
  computed: {
    curStyleClass () {
      return  this.styleList[this.curStyleIndex].name
    },
    tip () {
      let tip = ''
      if(this.curStyleClass === 'imageTextStyle1-3' || this.curStyleClass === 'imageTextStyle1-4' ) {
        tip = '建议上传.jpg/.jpeg/.png 格式，尺寸比例为 2:1，大小≤1M'
      } else if(this.curStyleClass === 'imageTextStyle1-5' || this.curStyleClass === 'imageTextStyle1-6' ) {
        tip = '建议上传.jpg/.jpeg/.png 格式，尺寸比例为 3:4，大小≤1M'
      } else if(this.curStyleClass === 'imageTextStyle4-1') {
        tip = '建议上传.jpg/.jpeg/.png 格式，尺寸比例为 16:9，大小≤1M'
      } else {
        tip = '建议上传.jpg/.jpeg/.png 格式，尺寸比例为 4:3，大小≤1M'
      }
      return tip
    }

  },
  mounted() {},
  components: { Drawer, Swiper, SvgIcon, draggable },
  methods: {
    sortDraggable (index, {oldIndex,newIndex}){
      let list = this.list
      for(let j = 0; j < list.length; j++ ){
        let data = JSON.parse(JSON.stringify(list[j].data))
        let arr = data.slice(oldIndex, oldIndex+1)[0]
        let arr2 = data.slice(newIndex, newIndex+1)[0]
        data[oldIndex] = arr2
        data[newIndex] = arr
        list[j].data = data
        this.$set(this.list[j], 'data', data)
        
      }
      this.list = list
      this.setCurDataItem(newIndex)
    },
    removeDataItem (index){ // 图文删除
      for(let i = 0; i < this.list.length;i++){
        this.list[i].data.splice(index, 1)        
      }
      let m = index - 1
      if(m>=0){
        this.setCurDataItem(m)
      } else {
        m = index + 1
        this.setCurDataItem(m)
      }
    },
    setCurDataItem(index){ // 预览选中的时候 样式展示跟着变
      this.curDataIndex = index
      for(let i = 0; i < this.list.length;i++){
        this.list[i].curImageList = this.list[i].data.length ? this.list[i].data[this.curDataIndex].data : []
      }
     this.setCurStyleIndex(this.list[0].data[this.curDataIndex].data[0].image_style)
    },
    changeTitle (value, index, contentI){ // 当前图文改变标题同步到列表中
      this.list[index].data[this.curDataIndex].data[contentI].title = value
    },
    changeDescription (value, index, contentI){// 当前图文改变描述同步到列表中
      this.list[index].data[this.curDataIndex].data[contentI].description = value
    },
    slidePrev(){ // 样式翻页
      let index = 0
      if(this.curStyleIndex > 0){
        index = this.curStyleIndex -=1
      }
      // let item = this.styleList[index]
      // this.setCurstyleItem(item,index)

    },
    slideNext(){// 样式翻页
      let index  = this.styleList.length - 1
      if (this.curStyleIndex <  index) {
        index = this.curStyleIndex +=1
      }
      // let item = this.styleList[index]
      // this.setCurstyleItem(item, index)
    },
    // 设置当前的样式
    setCurstyleItem(item, index){
      let num = item.num
      if(this.curStyleNum !== item.num){
        this.curStyleNum = num
      }
      this.curStyleIndex = index
      this.setCurImageList(num, item.type)
    },
    setCurImageList (params, type = '') { // 设置当前图文的数组
      let array = []
      if(typeof params == 'number'){
        for(let i = 0; i < params; i++){
          let obj = {
            image: '',
            title: '',
            description: '',
            image_style: this.curStyleClass,
            id: ''
          }
          array.push(obj)
        }
      }
      this.curDataIndex = this.list[0].data.length
      let listItem = {
         image_style: this.curStyleClass,
         data:  JSON.parse(JSON.stringify(array))
      }
      for(let i = 0; i < this.list.length; i++){
        this.$set(this.list[i], 'curImageList', JSON.parse(JSON.stringify(array)))
        this.list[i].data.push(JSON.parse(JSON.stringify(listItem)))
        this.list[i].curImageList = JSON.parse(JSON.stringify(array))
      }
      this.setCurDataItem(this.curDataIndex)
    },
    swiperScrollBy (){ // swiper 保证当前选中显示在窗口内
      let sw = document.getElementsByClassName('swiper-container')
      let active = sw[0].getElementsByClassName('active')[0].offsetTop - 86
      sw[0].scroll({
        top: active,
        left: 0,
        behavior: 'smooth'
      });
    },
    isCloseDrawer(index) {
      this.showDrawer = true;
      this.contentI = index;
    },
    setCurStyleIndex(style){ // 根据样式名找到当前显示的样式
      for(let i = 0; i < this.styleList.length; i++){
        if(this.styleList[i].name == style){
          this.curStyleIndex = i
          break;
        }
      }
    },
    // 获取图文详情
    getProductImage () {
      let params = {
        product_id: this.id
      }
      this.loading = true
      productImageGet(params).then(res=>{
        let list = res.data
        this.list = list
        
        if(list[0].data.length == 0){
          this.setCurstyleItem(this.styleList[0], 0)
        }else {
          let style = list[0].data[0].image_style
          for(let m = 0; m < list.length;m++){
            list[m].curImageList = list[m].data[0].data
          }
          this.setCurStyleIndex(style)

        }  
        this.curDataIndex  = 0
        this.activeName= list[0].site      
        this.loading = false


      })
    },
    // 图库选择是否显示
    closeDrawerDialog(data) {
      this.showDrawer = !this.showDrawer;
      if (data && data.filePathNameHttp) {
          let list = this.list;
          for (let i = 0; i < list.length; i++) {
            let curImageList = list[i].curImageList
            let dataItem = list[i].data[this.curDataIndex].data[this.contentI];
            dataItem.image = data.filePathName;
            dataItem.httpImage = data.filePathNameHttp;
            curImageList[this.contentI].image = data.filePathName;
            curImageList[this.contentI].httpImage = data.filePathNameHttp;
          }
      }
    },

  
    cancle() {
      this.$emit("closeDialog");
    },
    handleSuccess(response, res, fileList, contentI) {
      // console.log(response, res, fileList);
      let list = this.list;
      this.contentI = contentI
      for (let i = 0; i < list.length; i++) {
        let curImageList = list[i].curImageList
        let data = list[i].data[this.curDataIndex].data[contentI];
        data.image = response.data.filePathName;
        data.httpImage = response.data.filePathNameHttp;
        curImageList[contentI].image = response.data.filePathName;
        curImageList[contentI].httpImage = response.data.filePathNameHttp;
      }
      this.$message.success("上传图片成功");
      this.uploadLoading = false
    },

    handleError() {
      this.$message.error("上传图片失败");
      this.uploadLoading = false
    },

    beforeUpload(file) {
      let that = this;
      const isLt2M = file.size / 1024 <= 1024;
      if (!isLt2M) {
        this.$message.error("上传图片大小不超过1M");
        return false;
      }
      if (file.type !== "image/jpeg" && file.type !== "image/jpg" && file.type !== "image/png") {
        this.$message.error("仅支持.jpg/.jpeg/.png格式的图片");
        return false;
      }
      this.uploadLoading = true
      const isSize = new Promise(function (resolve, reject) {
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function () {
          // let valid = img.width/img.height == 4/3 ;
          let valid = true;
          valid ? resolve() : reject();
          let imgW = img.width;
          let imgH = img.height;
          if (imgW > imgH) {
            that.imgW = (imgH * 4) / 3;
            that.imgH = imgH;
          } else if (imgW <= imgH) {
            that.imgH = (imgW * 3) / 4;
            that.imgW = imgW;
          }
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          that.$message.error("上传图片尺寸为4:3");
          return Promise.reject();
        }
      );
      return isSize;
    },

    submitForm () {
      let status = this.validateForm()
      if(status){
        this.updateTag()
      }
    },
    validateForm () {
      let status = true;
      let list  = this.list 
      for(let i in list){
        let data =  list[i].data
        for(let j = 0; j < data.length; j++  ){
          for(let m = 0; m < data[j].data.length; m++){
            let dataItem = data[j].data[m]
            if(dataItem.image == '' && dataItem.image_style !== 'imageTextStyle4-2'){
              this.$message.error('站点' + list[i].site + '图文'+ (j +1) +'第'+(m+1)+'张图片为必填项')
              status = false
              return ;
            }
          }
 
        }
      }
      return status
    },
    updateTag () {
      if (!this.isRequest){
        this.isRequest = true
        let list =JSON.parse(JSON.stringify(this.list)) 
        for(let i = 0; i < list.length; i++){
          let data =  list[i].data
          for(let j = 0; j < data.length; j++){
            data[j].title_key = '图文' + (j+1)
            data[j].product_basic_id = list[i].product_basic_id
            data[j].site_id = list[i].id
            for(let m = 0; m < data[j].data.length; m++){
              let dataItem = data[j].data[m]
              dataItem.image_style =  data[j].image_style
              dataItem.title_key =  data[j].title_key
              dataItem.product_basic_id =  data[j].product_basic_id
              dataItem.product_id =  this.id
              dataItem.site_id =  data[j].site_id
              dataItem.site =  list[i].site
            }
          }
          delete list[i].curImageList

        }
        let params = { 
          data: JSON.stringify(list),
          product_id: this.id
        }
        productImagePost(params).then(res=>{
          if(res.state == 1){
            this.$message.success('保存成功')
            this.cancle()
          }
           this.isRequest = false
        })
    
      }
      },
  },
};
</script>

<style lang="scss" scoped>
  .imageText {
    /deep/ .swiper-wrapper {
      overflow: auto;
    }
    .styleItem {
      position: relative;
      border: 1px solid #6C7E59;
      border-radius: 5px;
      opacity: .4;

      &:hover {
        opacity: 1;
      }
      .icon-select {
        position: absolute;
        right: -2px;
        bottom: -2px;
        font-size: 32px;
        color: #6C7E59;
        display: none;
      }
    }
    .styleItem.active {
      opacity: 1;
      .icon-select {
        display: block;
      }
    }
  }
  // .module_preview {
    
  // }
</style>